﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

namespace WebApplication_hw0508.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TodoController : Controller
    {
        private static List<TodoItem> todoItems = new List<TodoItem>
        {
            new TodoItem { Id = 1, Name = "Learn C#", IsComplete = false },
            new TodoItem { Id = 2, Name = "Build a RESTful API", IsComplete = false },
            new TodoItem { Id = 3, Name = "Deploy to Azure", IsComplete = false }
        };

        [HttpGet]
        public IEnumerable<TodoItem> Get()                                  // 返回所有待办事项
        {
            return todoItems;
        }

        [HttpGet("{id}")]
        public ActionResult<TodoItem> Get(int id)                           // 根据 ID 返回单个待办事项
        {
            var item = todoItems.FirstOrDefault(i => i.Id == id);
            if (item == null)
            {
                return NotFound();
            }

            return item;
        }

        [HttpPost]
        public ActionResult<TodoItem> Post(TodoItem item)                   // 创建新的待办事项
        {
            item.Id = todoItems.Count + 1;
            todoItems.Add(item);
            return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
        }

        [HttpPut("{id}")]
        public IActionResult Put(int id, TodoItem item)                     // 按 ID 修改现有待办事项
        {
            var index = todoItems.FindIndex(i => i.Id == id);
            if (index == -1)
            {
                return NotFound();
            }

            todoItems[index] = item;
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)                                 // 按 ID 删除现有待办事项
        {
            var index = todoItems.FindIndex(i => i.Id == id);
            if (index == -1)
            {
                return NotFound();
            }

            todoItems.RemoveAt(index);
            return NoContent();
        }
    }
    public class TodoItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}
